import requests
import json
from retrying import retry
import time
import sys

# ZH_CN2EN 中文　»　英语
# ZH_CN2JA 中文　»　日语
# ZH_CN2KR 中文　»　韩语
# ZH_CN2FR 中文　»　法语
# ZH_CN2RU 中文　»　俄语
# ZH_CN2SP 中文　»　西语
# EN2ZH_CN 英语　»　中文
# JA2ZH_CN 日语　»　中文
# KR2ZH_CN 韩语　»　中文
# FR2ZH_CN 法语　»　中文
# RU2ZH_CN 俄语　»　中文
# SP2ZH_CN 西语　»　中文

def get_text(url):
    response = requests.get(url)
    response.encoding = "utf-8"
    return response.text

@retry(stop_max_attempt_number=3)
def translate(text, method):
    if text == "" or text == "\n":
        return ""
    url = f"https://fanyi.youdao.com/translate?&doctype=json&type={method}&i={text}"
    c = get_text(url)
    try:
        return json.loads(c)["translateResult"][0][0]["tgt"]
    except Exception as e:
        print(Exception(c, e))
        print("出现错误-请排查问题后按回车键继续")
        input()
        raise

translate_list = [
    # 顺序-中英日韩法俄西
    "ZH_CN2EN",
    # "ZH_CN2JA",
    # "ZH_CN2KR",
    # "ZH_CN2FR",
    # "ZH_CN2RU",
    # "ZH_CN2SP"
]

translate_list_arc = [
    # 顺序-中英日韩法俄西
    "EN2ZH_CN",
    # "JA2ZH_CN",
    # "KR2ZH_CN",
    # "FR2ZH_CN",
    # "RU2ZH_CN",
    # "SP2ZH_CN"
]

all_req_num = 0

def main(text, round, output=False):
    global all_req_num
    if output:
        print("输入:", text)
    final_text = text
    for x in range(round):# x为轮数
        if output:
            print(f"第{x+1}轮翻译", f"累计请求{all_req_num}次")
        for y in range(len(translate_list)):
            final_text = translate(final_text, translate_list[y])
            if output:
                print(final_text, translate_list[y], "(汉译英)")
            final_text = translate(final_text, translate_list_arc[y])
            if output:
                print(final_text, translate_list_arc[y], "(英译汉)")
                all_req_num += 2
    # print("执行输出")
    return final_text

# main("", 10, True)

# 批处理
if __name__ == "__main__":
    with open("./youdao-input.txt", "r") as f:
        content = f.readlines()

    print("文件已载入")

    with open("./youdao-output.txt", "w") as f:
        for y, x in enumerate(content):
            print("*"*10, f"{y}/{len(content)},,{round(y/len(content)*100, 2)}%", "*"*10)
            f.write(main(x, 5, True) + "\n")

    print("完成")
    input()
